use serde::Deserialize;
use rbatis::RBatis;
use rbdc_pool_fast::FastPool;
use rbdc_mysql::MysqlDriver;
use rbdc_mysql::options::MySqlConnectOptions;
use crate::APP_CONFIG;

/// 数据库配置参数
#[derive(Debug, Deserialize, Clone)]
pub struct DatabaseConfig {
    /// 数据库连接地址
    pub url: String,
    /// 数据库连接地址
    pub host: String,
    /// 数据库连接端口
    pub port: u16,
    /// 连接用户名称
    pub username: String,
    /// 连接密码
    pub password: String,
    /// 数据库名称
    pub database_name: String,
}

/// 数据库连接实现
impl DatabaseConfig {
    /// 初始化连接池
    pub fn init_connect_pool() -> RBatis {
        let rb = RBatis::new();

        let opts = MySqlConnectOptions::new()
            .host(&APP_CONFIG.database.host)
            .port(APP_CONFIG.database.port)
            .username(&APP_CONFIG.database.username)
            .password(&APP_CONFIG.database.password)
            .database(&APP_CONFIG.database.database_name);

        rb.init_option::<MysqlDriver, MySqlConnectOptions, FastPool>(MysqlDriver {}, opts).unwrap();
        rb

        // let mut opts = MySqlConnectOptions::new();
        // opts.set_uri(&APP_CONFIG.database.url).unwrap();
        // opts = opts.username(&APP_CONFIG.database.username)
        //     .password(&APP_CONFIG.database.password)
        //     .database(&APP_CONFIG.database.database_name);

        // let pool = FastPool::new(ConnManager::new_option(MysqlDriver {}, opts)).unwrap();
        // let pool = FastPool::new(ConnManager::new(MysqlDriver {}, &APP_CONFIG.database.url).unwrap()).unwrap();
        // rb.init_pool(pool).unwrap();
        // rb
    }
}
